"""
客户管理业务逻辑服务
"""
from datetime import datetime
from sqlalchemy import func
from app.extensions import db
from app.models.customer import Customer
from app.models.staff import Staff
from app.models.negotiation import Negotiation


class CustomerService:
    """客户管理服务"""
    
    @staticmethod
    def get_customers_with_pagination(page=1, per_page=20, search_name='', search_project='', search_cooperation_ended=''):
        """获取分页的客户列表"""
        query = Customer.query
        
        if search_name:
            query = query.filter(Customer.name.contains(search_name))
        if search_project:
            query = query.filter(Customer.project_number.contains(search_project))
        if search_cooperation_ended:
            ended = search_cooperation_ended == 'true'
            query = query.filter(Customer.is_cooperation_ended == ended)
        
        return query.paginate(page=page, per_page=per_page, error_out=False)
    
    @staticmethod
    def get_dropdown_data():
        """获取下拉选项数据"""
        project_numbers = db.session.query(Customer.project_number).distinct().all()
        suitable_managers = db.session.query(Staff.name).all()
        
        return {
            'project_numbers': [p[0] for p in project_numbers if p[0]],
            'suitable_managers': [s[0] for s in suitable_managers]
        }
    
    @staticmethod
    def create_customer(data):
        """创建客户"""
        customer = Customer(
            name=data.get('name'),
            project_number=data.get('project_number'),
            gender=data.get('gender'),
            start_date=datetime.strptime(data.get('start_date'), '%Y-%m-%d').date() if data.get('start_date') else None,
            end_date=datetime.strptime(data.get('end_date'), '%Y-%m-%d').date() if data.get('end_date') else None,
            suitable_manager=data.get('suitable_manager'),
            notes=data.get('notes'),
            is_cooperation_ended=data.get('is_cooperation_ended') == 'on',
            industry=data.get('industry', ''),
            contact_person=data.get('contact_person', ''),
            contact_phone=data.get('contact_phone', ''),
            contact_email=data.get('contact_email', ''),
            address=data.get('address', ''),
            description=data.get('description', '')
        )
        
        # 自动计算合作天数
        customer.calculate_cooperation_days()
        
        db.session.add(customer)
        db.session.commit()
        return customer
    
    @staticmethod
    def update_customer(customer_id, data):
        """更新客户信息"""
        customer = Customer.query.get_or_404(customer_id)
        
        customer.name = data.get('name')
        customer.project_number = data.get('project_number')
        customer.gender = data.get('gender')
        customer.start_date = datetime.strptime(data.get('start_date'), '%Y-%m-%d').date() if data.get('start_date') else None
        customer.end_date = datetime.strptime(data.get('end_date'), '%Y-%m-%d').date() if data.get('end_date') else None
        customer.suitable_manager = data.get('suitable_manager')
        customer.notes = data.get('notes')
        customer.is_cooperation_ended = data.get('is_cooperation_ended') == 'on'
        customer.updated_at = datetime.utcnow()
        
        # 更新新增字段
        customer.industry = data.get('industry', '')
        customer.contact_person = data.get('contact_person', '')
        customer.contact_phone = data.get('contact_phone', '')
        customer.contact_email = data.get('contact_email', '')
        customer.address = data.get('address', '')
        customer.description = data.get('description', '')
        
        # 自动重新计算合作天数
        customer.calculate_cooperation_days()
        
        db.session.commit()
        return customer
    
    @staticmethod
    def delete_customer(customer_id):
        """删除客户"""
        customer = Customer.query.get_or_404(customer_id)
        db.session.delete(customer)
        db.session.commit()
        return True
    
    @staticmethod
    def get_all_customers():
        """获取所有客户"""
        return Customer.query.all()
    
    @staticmethod
    def get_customer_statistics():
        """获取客户统计信息"""
        total_customers = Customer.query.count()
        current_year_customers = Customer.query.filter(
            func.strftime('%Y', Customer.created_at) == str(datetime.now().year)
        ).count()
        
        return {
            'total_customers': total_customers,
            'current_year_customers': current_year_customers
        }
